<template>
  <div :class="['comment-container u-s', isMtype ? 'p-t-m' : '']">
    <img
      class="close-img cu"
      @click="closePage"
      src="//image.zlketang.com/public/news/others/imgs/web_pc/0b4e7a0e5fe84ad35fb5f95b9ceeac79.png"
    />
    <el-tabs
      v-if="isMtype"
      v-model="activeIndex"
      @tab-click="handleChangeActive"
      class="tab-list"
    >
      <el-tab-pane
        v-for="(item, index) in currentQuestion.options"
        :key="index"
        :label="'第' + (index + 1) + '小题'"
        :name="index + ''"
      ></el-tab-pane>
    </el-tabs>
    <div
      ref="commentContentRef"
      class="comment-content"
      :class="{
        'comment-tab-content':
          Array.isArray(currentQuestion.options) &&
          currentQuestion.options.length
      }"
    >
      <div
        class="comment-tab flex-wrap"
        :style="{
          top:
            Array.isArray(currentQuestion.options) &&
            currentQuestion.options.length
              ? '64px'
              : '10px'
        }"
      >
        <div class="tab-box" @click="handleTriggerComments(1)">
          <div class="title" :class="+commentType === 1 ? 'active-title' : ''">
            精彩讨论（{{
              (currentComment.sticks && currentComment.sticks.length) || 0
            }}）
          </div>
          <div v-show="+commentType === 1" class="tab-line"></div>
        </div>
        <div class="tab-box" @click="handleTriggerComments(2)">
          <div class="title" :class="+commentType === 2 ? 'active-title' : ''">
            最新讨论（{{ currentComment.total || 0 }}）
          </div>
          <div v-show="+commentType === 2" class="tab-line"></div>
        </div>
      </div>

      <!-- 精彩评论 -->
      <!-- v-if="currentComment.sticks && currentComment.sticks.length != 0" -->
      <!-- <div class="part-title">精彩讨论</div> -->
      <template v-if="+commentType === 1">
        <div
          class="comment-zhanwei"
          v-if="
            !Array.isArray(currentComment.sticks) ||
              !currentComment.sticks.length
          "
        >
          快发表你的看法，和考友一起交流心得吧
        </div>
        <div
          v-for="(item, index) in currentComment.sticks"
          :key="index"
          class="singgle-comment-box"
        >
          <div
            class="single-comment-wrap"
            v-if="
              currentComment.sticks &&
                currentComment.sticks.length != 0 &&
                +item.review !== 2
            "
          >
            <div class="flex-wrap">
              <!-- 评论内容 -->
              <div>
                <img
                  class="head-img"
                  :src="parseResourceUrl(item.headimgurl)"
                  alt=""
                />
              </div>
              <div class="comment-r flex1">
                <div class="comment-nickname">{{ item.nickname }}</div>
                <div
                  class="comment-content-wrap"
                  v-html="parseHtmlUrl(item.comment)"
                ></div>
                <div class="comment-des flex-center-wrap flex-justify-between">
                  <div class="comment-time">{{ handleTime(item.time) }}</div>
                  <div
                    class="comment-like-wrap"
                    @click="thumb(item)"
                    :class="{
                      'comment-like-active': likes[item.object_id]
                    }"
                  >
                    {{ item.thumbs }}
                    <i class="iconfont icon-zan"></i>
                  </div>
                  <div class="comment-huifu" @click="addReply(item)">
                    <i class="iconfont icon-pinglun"></i>
                  </div>
                </div>
                <!-- 回复 -->
                <div
                  class="all-replys-container"
                  v-if="item.replys && !item.replys.length"
                >
                  <div
                    class="reply-item"
                    v-for="(replyItem, replyIndex) in item.replys"
                    :key="replyIndex"
                  >
                    <div
                      class="single-reply-wrap flex-wrap"
                      v-if="+replyItem.review !== 2"
                    >
                      <div>
                        <img
                          class="reply-head-img"
                          :src="parseResourceUrl(replyItem.headimgurl)"
                          alt=""
                        />
                      </div>
                      <div class="comment-r flex1">
                        <div class="reply-nickname">
                          {{ replyItem.nickname }}
                          <i
                            class="iconfont icon-hudongbofanganniu reply-icon"
                          ></i>
                          {{ replyItem.reply_nickname }}
                        </div>
                        <div
                          class="comment-content-wrap"
                          v-html="parseHtmlUrl(replyItem.comment)"
                        ></div>
                        <div
                          class="comment-des flex-center-wrap flex-justify-between"
                        >
                          <div class="comment-time">
                            {{ handleTime(replyItem.time) }}
                          </div>
                          <div
                            class="comment-like-wrap"
                            @click="thumb(replyItem)"
                            :class="{
                              'comment-like-active': likes[replyItem.object_id]
                            }"
                          >
                            {{ replyItem.thumbs }}
                            <i class="iconfont icon-zan"></i>
                          </div>
                          <div
                            class="comment-huifu"
                            @click="addReply(item, replyItem)"
                          >
                            <i class="iconfont icon-pinglun"></i>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    class="reply-more-wrap"
                    v-if="
                      item.reply_total > 2 &&
                        item.replys.length < item.reply_total
                    "
                    @click="getMoreComments(item)"
                  >
                    共 {{ item.reply_total }} 条回复
                    <i class="iconfont icon-xiala1"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </template>
      <!-- 最新评论 -->
      <template v-if="+commentType === 2">
        <div
          class="comment-zhanwei"
          v-show="
            showContent &&
              (!Array.isArray(currentComment.comments) ||
                !currentComment.comments.length)
          "
        >
          快发表你的看法，和考友一起交流心得吧
        </div>
        <div
          v-show="
            Array.isArray(currentComment.comments) &&
              currentComment.comments.length
          "
        >
          <div
            v-for="item in currentComment.comments"
            :key="item.object_id"
            class="singgle-comment-box"
          >
            <!-- v-if="+item.review !== 2" -->
            <div class="flex-wrap single-comment-wrap">
              <div>
                <img
                  class="head-img"
                  :src="parseResourceUrl(item.headimgurl)"
                  alt=""
                />
              </div>
              <div class="comment-r flex1">
                <div class="comment-nickname">{{ item.nickname }}</div>
                <div
                  class="comment-content-wrap"
                  v-html="parseHtmlUrl(item.comment)"
                ></div>
                <div class="comment-des flex-center-wrap flex-justify-between">
                  <div class="comment-time">{{ handleTime(item.time) }}</div>
                  <div
                    class="comment-like-wrap"
                    @click="thumb(item)"
                    :class="{
                      'comment-like-active': likes[item.object_id]
                    }"
                  >
                    {{ item.thumbs }}
                    <i class="iconfont icon-zan"></i>
                  </div>
                  <div class="comment-huifu" @click="addReply(item)">
                    <i class="iconfont icon-pinglun"></i>
                  </div>
                </div>
                <!-- 回复 -->
                <div
                  class="all-replys-container"
                  v-if="item.replys && item.replys.length != 0"
                >
                  <div
                    class="reply-item"
                    v-for="(replyItem, replyIndex) in item.replys"
                    :key="replyIndex"
                  >
                    <div
                      class="single-reply-wrap flex-wrap"
                      v-if="+replyItem.review !== 2"
                    >
                      <div>
                        <img
                          class="reply-head-img"
                          :src="parseResourceUrl(replyItem.headimgurl)"
                          alt=""
                        />
                      </div>
                      <div class="comment-r flex1">
                        <div class="reply-nickname">
                          {{ replyItem.nickname }}
                          <i
                            class="iconfont icon-hudongbofanganniu reply-icon"
                          ></i>
                          {{ replyItem.reply_nickname }}
                        </div>
                        <div
                          class="comment-content-wrap"
                          v-html="parseHtmlUrl(replyItem.comment)"
                        ></div>
                        <div
                          class="comment-des flex-center-wrap flex-justify-between"
                        >
                          <div class="comment-time">
                            {{ handleTime(replyItem.time) }}
                          </div>
                          <div
                            class="comment-like-wrap"
                            @click="thumb(replyItem)"
                            :class="{
                              'comment-like-active': likes[replyItem.object_id]
                            }"
                          >
                            {{ replyItem.thumbs }}
                            <i class="iconfont icon-zan"></i>
                          </div>
                          <div
                            class="comment-huifu"
                            @click="addReply(item, replyItem)"
                          >
                            <i class="iconfont icon-pinglun"></i>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div
                    class="reply-more-wrap"
                    v-if="
                      item.reply_total > 2 &&
                        item.replys.length < item.reply_total
                    "
                    @click="getMoreComments(item)"
                  >
                    共 {{ item.reply_total }} 条回复
                    <i class="iconfont icon-xiala1"></i>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- 更多评论 -->
        <div
          class="load-more-wrap flex-center"
          v-if="
            currentComment.comments &&
              currentComment.comments.length >= 3 &&
              currentComment.comments.length < currentComment.comment_total
          "
        >
          <el-button type="primary" round size="small" @click="getMoreComments">
            加载更多
          </el-button>
        </div>
      </template>

      <!-- 最新讨论 -->
      <!-- <div class="part-title">最新讨论（{{ currentComment.total || 0 }}）</div> -->
    </div>
    <div class="comment-input">
      <div class="flex-wrap flex-justify-end mb5">
        <el-button
          type="primary"
          size="mini"
          :disabled="isDisabledBtn"
          @click.stop="addComment"
        >
          提交
        </el-button>
      </div>
      <el-input
        ref="commentInput"
        type="textarea"
        :autosize="{ minRows: 3, maxRows: 3 }"
        resize="none"
        v-model="commentContent"
        :placeholder="commentPlaceholder"
      ></el-input>
    </div>
    <zl-drag-verify
      v-if="isShowDragVerify"
      @success="onDragVerifySuccess"
      @close="isShowDragVerify = false"
    ></zl-drag-verify>
  </div>
</template>

<script>
import dragVerify from '@/components/dragVerify.vue'
import {
  getExamComments,
  getSingleExamComments,
  getMoreExamComments,
  saveExamComment
} from '@/api/exam'
export default {
  name: 'cpaComments',
  components: {
    'zl-drag-verify': dragVerify
  },
  props: {
    analysisPage: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      // 是否显示滑块校验
      isShowDragVerify: false,
      allComments: {},
      // 点赞
      likes: {},
      // 显示内容
      showContent: false,
      // 当前评论
      currentComment: {
        comments: []
      },
      //
      currentUkey: '',
      commentContent: '', //评论或回复内容
      submitType: 'comment', // comment为评论，reply为回复
      commentPlaceholder: '我的看法是...',
      //回复参数
      replyPostData: {},
      // 当前回复的评论,回复时更新评论使用
      currentCommentItem: {},
      // 当前回复的回复,回复时更新评论使用
      currentReplyItem: {},
      // 埋点数据
      zlaBtn: {
        key_name: '',
        key_content: ''
      },
      // 当前讨论的小题号
      activeIndex: '0',
      isDisabledBtn: false,
      commentType: 1
    }
  },

  computed: {
    isMtype() {
      return (
        Array.isArray(this.currentQuestion.options) &&
        this.currentQuestion.options.length
      )
    },
    query() {
      return this.getQuery(location.search)
    },
    commonParams() {
      let { exam_id, exam_type, subject_id } = this.query
      return { exam_id, exam_type, subject_id }
    },
    currentQuestion() {
      return this.$store.state.exam.currentQuestion
    },
    // 组合题的小题号
    subQuestionIndex() {
      let { exam } = this.$store.state
      if (!exam) {
        return '0'
      }
      return this.$store.state.exam.subQuestionIndex || '0'
    },
    questionData() {
      let { exam } = this.$store.state
      if (!exam) {
        return {}
      }
      return this.$store.state.exam.currentQuestion || {}
    }
  },
  watch: {
    zlaBtn: {
      handler() {
        this.sendZlaClick()
      },
      deep: true
    }
  },
  activated() {
    this.init()
  },
  methods: {
    // 1 精彩评论  2 最新评论
    handleTriggerComments(val) {
      this.commentType = val
    },
    init() {
      // 重置数据
      this.isShowDragVerify = false
      this.allComments = {}
      this.likes = {}
      this.currentComment = {
        comments: [],
        sticks: [],
        total: 0
      }
      this.currentUkey = ''
      this.commentContent = ''
      this.submitType = 'comment'
      this.commentPlaceholder = '我的看法是...'
      this.replyPostData = {}
      this.currentCommentItem = {}
      this.currentReplyItem = {}
      this.activeIndex = '0'
      this.isDisabledBtn = false
      if (this.questionData.type === 3) {
        this.activeIndex = this.subQuestionIndex + ''
      }
      console.log('this.activeIndex', this.activeIndex)

      this.getComments()
      let arr = [
        { id: 1, name: '部门1', pid: 0 },
        { id: 2, name: '部门2', pid: 1 },
        { id: 3, name: '部门3', pid: 1 },
        { id: 4, name: '部门4', pid: 3 },
        { id: 5, name: '部门5', pid: 4 }
      ]
      let tree = (function(data, root) {
        var t = {}
        data.forEach(o => {
          Object.assign((t[o.id] = t[o.id] || {}), o)
          t[o.pid] = t[o.pid] || {}
          t[o.pid].children = t[o.pid].children || []
          t[o.pid].children.push(t[o.id])
        })
        if (!t[root]) {
          return []
        }
        return t[root].children
      })(arr, undefined)
    },
    closePage() {
      this.$emit('analysisPageChange', {
        page: ''
      })
    },
    //滑动验证码验证通过后，再次提交评论
    onDragVerifySuccess() {
      this.isShowDragVerify = false
    },
    getComments() {
      let params = {
        ...this.commonParams,
        from: 'wxpub',
        ukeys: {}
      }
      let { type, options, question_id, indexId } = this.currentQuestion
      // 综合题
      if (type === 3) {
        options.forEach((item, index) => {
          params.ukeys[`${question_id}_${index}`] = ''
        })
      } else {
        params.ukeys[indexId] = ''
      }
      // let ukey = this.currentQuestion.question_id + '_' + index
      if (this.allComments[`${question_id}_${this.activeIndex}`]) {
        return this.initComment()
      }
      getExamComments(params).then(res => {
        let { data, errcode } = res
        if (errcode !== 0) return
        let { comments, likes } = data
        this.allComments = Object.assign(this.allComments, comments)
        this.likes = likes
        this.initComment()
      })
    },
    // 初始化当前评论
    initComment() {
      let { question_id } = this.currentQuestion
      this.currentUkey = `${question_id}_${this.activeIndex}`
      this.currentComment = this.allComments[this.currentUkey] || {}
      this.showContent = true
    },
    handleTime(time) {
      var dateObj = new Date(time * 1000)
      let formateTime = this.formatDateTime({ dateObj: dateObj }).split('-')
      formateTime[2] =
        formateTime[2] < 10 ? `0${formateTime[2]}` : formateTime[2]
      return `${formateTime[1]}-${formateTime[2]}`
      // return this.formatDateTime({ dateObj: dateObj })
    },
    //操作评论
    addComment() {
      if (!this.commentContent.trim()) {
        return this.$message({
          type: 'warning',
          message: '评论或回复不能为空'
        })
      }
      // 最大长度1000
      if (this.commentContent.length > 1000) {
        return this.$message({
          type: 'warning',
          message: '评论或回复不能超过1000个字符'
        })
      }
      let params = {
        ...this.commonParams,
        from: 'web',
        ukey: this.currentUkey,
        comment: this.commentContent
      }
      let message = ''
      if (this.submitType === 'comment') {
        params.comment_type = 2
        message = '评论'
      } else {
        params = this.replyPostData
        params.comment = this.commentContent
        message = '回复'
      }
      this.isDisabledBtn = true
      saveExamComment(params)
        .then(res => {
          this.isDisabledBtn = false
          let { errcode, data, errmsg } = res
          if (+errcode === 1101) {
            return (this.isShowDragVerify = true)
          }
          if (+errcode === 1006) {
            return this.$message.error(errmsg)
          }
          this.commentContent = ''
          this.$message.success(`${message}成功`)
          let { total = 0, comments = [] } = this.currentComment
          if (this.submitType === 'comment') {
            // this.currentComment.comment_total = comment_total + 1
            // this.currentComment.comments = comments.unshift(data)
            comments.unshift(data)
            this.currentComment.total = total + 1
            this.currentComment.comments = comments
            // 保存已经发布的评论
            this.allComments[this.currentUkey] = this.currentComment
          } else {
            // 重置为发表评论模式
            this.submitType = 'comment'
            this.commentPlaceholder = '我的看法是...'
            let { reply_total, replys = [] } = this.currentCommentItem

            if (reply_total < 2) {
              replys.push(data)
            } else {
              this.currentCommentItem.reply_total = reply_total + 1
            }
            this.$forceUpdate()
          }
          this.zlaBtn = {
            key_name: '提交看法',
            key_content: '提交看法'
          }
          this.commentType = 2
          this.$refs.commentContentRef.scrollTo({
            top: 0,
            behavior: 'smooth'
          })
        })
        .catch(() => {
          this.isDisabledBtn = false
        })
    },
    getMoreComments(item) {
      let params = {
        ...this.commonParams,
        from: 'wxpub',
        start: 0,
        end: 0
      }
      // 加载题目更多回复
      if (!item.object_id) {
        let { comment_total, comments } = this.currentComment
        if (comment_total <= comments.length) return
        params.start = comments.length
        params.ukey = this.currentUkey
        params.comment_type = 2
      } else {
        // 加载单条评论更多回复
        let { reply_total, replys, object_id } = item
        if (reply_total <= replys.length) return
        params.start = replys.length
        params.object_id = object_id
        params.comment_type = 3
      }
      params.end = params.start + 10
      getMoreExamComments(params).then(res => {
        let { data, errcode } = res
        if (errcode !== 0) return
        let { comments, likes } = data
        if (item.object_id) {
          item.replys = [...item.replys, ...comments]
        } else {
          this.currentComment.comments = [
            ...this.currentComment.comments,
            ...comments
          ]
        }
        this.likes = Object.assign(this.likes, likes)
        this.allComments[this.currentUkey] = this.currentComment
        if (!comments.length) {
        }
      })
    },
    thumb(item) {
      let { object_id, thumbs } = item
      let params = {
        ...this.commonParams,
        from: 'web',
        ukey: this.currentUkey,
        object_id
      }
      // comment_type 1 添加点赞，4 取消点赞
      params.comment_type = this.likes[object_id] ? 4 : 1
      // 更新点赞数据
      saveExamComment(params).then(res => {
        let { errcode } = res
        if (+errcode === 1101) {
          return (this.isShowDragVerify = true)
        }
        if (params.comment_type === 4) {
          this.$set(this.likes, object_id, 0)
          item.thumbs = thumbs - 1
        } else {
          this.likes[object_id] = 1
          this.$set(this.likes, object_id, 1)
          item.thumbs = thumbs + 1
        }
      })
    },
    addReply(item, replyItem) {
      this.$refs.commentInput.focus()
      let { nickname, object_id } = item
      this.commentPlaceholder = '回复：' + nickname
      // 回复回复
      this.replyPostData = {
        ...this.commonParams,
        from: 'web',
        ukey: this.currentUkey,
        comment_type: 3,
        reply_nickname: nickname,
        object_id
      }
      if (replyItem) {
        this.replyPostData.reply_object_id = replyItem.object_id
        this.currentReplyItem = replyItem
      }
      this.currentCommentItem = item
      this.submitType = 'reply'
    },
    handleChangeActive(index) {
      this.initComment()
    },
    sendZlaClick() {
      this.keyClick({
        ...this.zlaBtn
      })
    }
  }
}
</script>

<style scoped>
.comment-container {
  position: fixed;
  right: 24px;
  top: 90px;
  bottom: 10px;
  width: 420px;
  padding: 50px 0;
  background: #fff;
  border-radius: 10px;
  z-index: 9;
  box-shadow: -2px 4px 20px #e6e6e6;
  word-break: break-all;
}
.p-t-m {
  padding-top: 32px;
}
.comment-zhanwei {
  padding: 16px 0;
  text-align: center;
  color: #999;
}
.comment-content {
  padding: 0 16px;
  height: calc(100% - 120px);
  overflow: auto;
}
.comment-tab-content {
  height: calc(100% - 186px);
}

.comment-tab .tab-box {
  position: relative;
  margin-right: 48px;
  padding-bottom: 8px;
}
.comment-tab {
  width: 390px;
  height: 50px;
  position: absolute;
  top: 10px;
  background-color: #fff;
  display: flex;
  align-items: center;
}
.tab-box .title {
  font-size: 20px;
  color: #999;
  line-height: 28px;
}
.active-title {
  color: #666 !important;
  font-weight: bold;
}

.tab-line {
  width: 48px;
  height: 3px;
  background: #02a9f4;
  position: absolute;
  bottom: 0px;
  left: 50%;
  transform: translateX(-50%);
}

.part-title {
  position: relative;
  margin-bottom: 12px 0 2px;
  padding-left: 8px;
  font-size: 18px;
  font-weight: bold;
  color: #666;
}
.part-title::before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  width: 3px;
  height: 18px;
  border-radius: 10px;
  background-color: #03a9f4;
  transform: translate(0, -50%);
}
.single-comment-wrap {
  padding: 12px 0;
  border-bottom: 1px solid #e6e6e6;
}
.singgle-comment-box:last-child .single-comment-wrap {
  border: none;
}
.head-img {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}
.reply-head-img {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}
.comment-r {
  margin-left: 8px;
}
.comment-nickname {
  margin-bottom: 4px;
  font-size: 16px;
  color: #666;
  font-weight: bold;
}
.comment-content-wrap {
  margin-bottom: 2px;
  font-size: 15px;
}
.comment-des {
  font-size: 14px;
  color: #666;
}
.comment-time {
  /* color: #999; */
}
.all-replys-container {
  margin-top: 8px;
  padding: 8px 8px 0;
  background: #fafafa;
  border-radius: 4px;
}
.reply-item {
  padding-bottom: 8px;
}
.reply-nickname {
  font-size: 14px;
  font-weight: bold;
  color: #666;
}
.reply-icon {
  font-size: 12px;
  transform: scale(0.8);
  color: #ccc;
}
.reply-more-wrap {
  padding: 0 8px;
  /* background: #f6f6f6; */
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
  border-radius: 4px;
}
.comment-like-wrap {
  cursor: pointer;
}
.comment-like-active {
  color: #ff5464;
}
.comment-huifu {
  cursor: pointer;
}
.comment-input {
  padding: 8px 16px 0;
}
.load-more-wrap {
  margin-top: 12px;
}
.tab-list {
  padding: 0 16px 12px;
  font-size: 16px;
  overflow-x: auto;
}
.tab-list /deep/ .el-tabs__item {
  padding: 0 10px;
}
.close-img {
  position: absolute;
  width: 16px;
  height: 16px;
  top: 16px;
  right: 16px;
  z-index: 999;
}
</style>
